package dictcn.com.activity;

import java.io.IOException;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tencent.weibo.api.UserAPI;
import com.tencent.weibo.constants.OAuthConstants;
import com.tencent.weibo.oauthv1.OAuthV1;
import com.tencent.weibo.oauthv1.OAuthV1Client;
import com.tencent.weibo.webview.OAuthV1AuthorizeWebView;
import com.weibo.sdk.android.Oauth2AccessToken;
import com.weibo.sdk.android.Weibo;
import com.weibo.sdk.android.WeiboAuthListener;
import com.weibo.sdk.android.WeiboDialogError;
import com.weibo.sdk.android.WeiboException;
import com.weibo.sdk.android.api.AccountAPI;
import com.weibo.sdk.android.api.UsersAPI;
import com.weibo.sdk.android.net.RequestListener;

import dictcn.com.R;
import dictcn.com.control.AccessQqTokenKeeper;
import dictcn.com.control.AccessSinaTokenKeeper;
import dictcn.com.model.AccessQqUserInfo;
import dictcn.com.model.AccessSinaUserId;
import dictcn.com.model.AccessSinaUserInfo;

public class AccoutSetting extends Activity {

	private TextView txt_account_info2;
	private TextView txt_accout_bind_info;
	private TextView txt_accout_bind_name;
	private TextView txt_account_info3;
	private LinearLayout layout_login;
	private Button btn_logout;
	private ImageButton btn_account_back;
	
	private RelativeLayout layout_sina_account;
	private RelativeLayout layout_renren_account;
	private RelativeLayout layout_qq_account;
	
	private static OAuthV1 oauth;	
	private static Weibo mWeibo;
	private static Oauth2AccessToken accessToken;
	
	private Handler myHandler=new Handler(){
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch(msg.what){
			case 1:
				if(accessToken!=null){
					
					if(!AccessSinaUserInfo.readUserInfo(AccoutSetting.this).equals("-1")){
						
						sinaBind();
						AccessSinaUserInfo.keepUserInfoBind(AccoutSetting.this, true);
						AccessQqUserInfo.keepQqUserBind(AccoutSetting.this, false);
						
					}else{
						Toast.makeText(AccoutSetting.this, "sina认证失败！", Toast.LENGTH_SHORT).show();
					}
				}
				break;
			case 3:
				Toast.makeText(AccoutSetting.this, "信息分享失败，网络连接失败！", Toast.LENGTH_SHORT).show();
				break;
			case 4:
				Toast.makeText(AccoutSetting.this, "网络连接失败！", Toast.LENGTH_SHORT).show();
				break;
			}
		}
	};
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.accout_setting);
		
		initView();
		
	}
	
	//初始化控件
	private void initView(){
		
		txt_account_info2=(TextView)findViewById(R.id.txt_accout_info2);
		txt_account_info3=(TextView)findViewById(R.id.txt_accout_info3);
		txt_accout_bind_info=(TextView)findViewById(R.id.txt_accout_bind_info);
		txt_accout_bind_name=(TextView)findViewById(R.id.txt_accout_bind_name);
		layout_login=(LinearLayout)findViewById(R.id.layout_login);
		btn_logout=(Button)findViewById(R.id.btn_logout);
		layout_sina_account=(RelativeLayout)findViewById(R.id.layout_sina_account);
		layout_qq_account=(RelativeLayout)findViewById(R.id.layout_qq_account);
		layout_renren_account=(RelativeLayout)findViewById(R.id.layout_renren_account);
		btn_account_back=(ImageButton)findViewById(R.id.imgbtn_acccount_back);
		
		//绑定图标及控件的显示
		isBind();
		
		btn_logout.setOnClickListener(new logOutClickListener());
		btn_account_back.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				AccoutSetting.this.finish();
			}
		});
		
		//新浪控件布局的监听事件
		layout_sina_account.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(!AccessSinaUserInfo.readUserInfo(AccoutSetting.this).equals("-1")){
					
					sinaBind();
					AccessSinaUserInfo.keepUserInfoBind(AccoutSetting.this, true);
					AccessQqUserInfo.keepQqUserBind(AccoutSetting.this, false);
					
				}else{
					
					CookieSyncManager.createInstance(AccoutSetting.this);  
					CookieSyncManager.getInstance().startSync();  
					CookieManager.getInstance().removeAllCookie();
					mWeibo=Weibo.getInstance("1825331322", "http://www.sina.com");
					mWeibo.authorize(AccoutSetting.this, new SinaAuthDlgListener());
				}
			}
		});
		
		
		//腾讯布局控件的监听事件
		layout_qq_account.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(!AccessQqUserInfo.readQqUser(AccoutSetting.this).equals("-1")){
					
					qqBind();
					AccessSinaUserInfo.keepUserInfoBind(AccoutSetting.this, false);
					AccessQqUserInfo.keepQqUserBind(AccoutSetting.this, true);
					
				}else{
					
					if(oauth==null)
						oauth=new OAuthV1("null");
						oauth.setOauthConsumerKey("801351500");
						oauth.setOauthConsumerSecret("af525481caa63b51babedaaa8f1d53e5");
					try {
			        	oauth=OAuthV1Client.requestToken(oauth);
			        } catch (Exception e) {
			            e.printStackTrace();
			        }
			        
		        	Intent intent = new Intent(AccoutSetting.this, OAuthV1AuthorizeWebView.class);
		            intent.putExtra("oauth", oauth);
		            startActivityForResult(intent,123); 
				}
			}
		});
		
	}
	
	//注销绑定按钮监听事件
	private class logOutClickListener implements OnClickListener{
		
		public void onClick(View v) {
			// TODO Auto-generated method stub
			
			//注销新浪用户
			if(txt_accout_bind_info.getText().toString().trim().equals("新浪微博账号：")){
				
				CookieSyncManager.createInstance(AccoutSetting.this);  
				CookieSyncManager.getInstance().startSync();  
				CookieManager.getInstance().removeAllCookie();
				AccessSinaTokenKeeper.clearSinaToken(AccoutSetting.this);
				AccessSinaUserInfo.clearUserInfo(AccoutSetting.this);				
			//注销腾讯用户
			}else if(txt_accout_bind_info.getText().toString().trim().equals("腾讯微博账号：")){
				
				AccessQqTokenKeeper.clearQqToken(AccoutSetting.this);
				AccessQqUserInfo.clearQqUser(AccoutSetting.this);
			//注销人人网账号	
			}else if(txt_accout_bind_info.getText().toString().trim().equals("人人网账号：")){
				
				
			}	
			//重新显示布局
			nonBind();
		}
	}
	
	//布局显示
	private void isBind(){
		
		if(AccessQqUserInfo.readQqUserBind(AccoutSetting.this)==false&&
				AccessSinaUserInfo.readUserInfoBind(AccoutSetting.this)==false){
			//当前没有登陆用户
			nonBind();
			
		}else if(AccessQqUserInfo.readQqUserBind(AccoutSetting.this)){
			//当前为腾讯账号登陆
			qqBind();
			
		}else if(AccessSinaUserInfo.readUserInfoBind(AccoutSetting.this)){
			//当前用户为新浪账号登陆
			sinaBind();
		}else{
			//当前用户为人人网用户
		}	
	}
	
	// sina is bind
	public void sinaBind(){
		txt_account_info2.setVisibility(View.VISIBLE);
		layout_login.setVisibility(View.VISIBLE);
		
		txt_account_info3.setText("其它登陆方式");
		txt_accout_bind_info.setText("新浪微博账号：");
		txt_accout_bind_name.setText(AccessSinaUserInfo.readUserInfo(AccoutSetting.this));
		
		btn_logout.setVisibility(View.VISIBLE);
		
		layout_qq_account.setVisibility(View.VISIBLE);
		layout_sina_account.setVisibility(View.GONE);
		layout_renren_account.setVisibility(View.VISIBLE);
	}
	
	//qq is bind
	public void qqBind(){
		txt_account_info2.setVisibility(View.VISIBLE);
		layout_login.setVisibility(View.VISIBLE);
		
		txt_account_info3.setText("其它登陆方式");
		txt_accout_bind_info.setText("腾讯微博账号：");
		txt_accout_bind_name.setText(AccessQqUserInfo.readQqUser(AccoutSetting.this));
		
		btn_logout.setVisibility(View.VISIBLE);
		
		layout_qq_account.setVisibility(View.GONE);
		layout_sina_account.setVisibility(View.VISIBLE);
		layout_renren_account.setVisibility(View.VISIBLE);
	}
	
	//non account is bind
	public void nonBind(){
		txt_account_info2.setVisibility(View.GONE);
		layout_login.setVisibility(View.GONE);
		btn_logout.setVisibility(View.GONE);
		
		txt_account_info3.setText("选择登陆方式");
		
		layout_qq_account.setVisibility(View.VISIBLE);
		layout_sina_account.setVisibility(View.VISIBLE);
		layout_renren_account.setVisibility(View.VISIBLE);
	}

	/*
	 * 下面大部分为腾讯及新浪的用户绑定及用户名的获取信息代码，以后要重构！！！！！！！！
	 */
	public class SinaAuthDlgListener implements WeiboAuthListener{
		
		public void onComplete(Bundle values) {
			// TODO Auto-generated method stub
			String token=values.getString("access_token");
			String expires_in=values.getString("expires_in");
			AccoutSetting.accessToken=new Oauth2AccessToken(token,expires_in);
			if(AccoutSetting.accessToken.isSessionValid()){			
				AccessSinaTokenKeeper.keepSinaAccessToken(AccoutSetting.this, accessToken);
				
				AccountAPI accountAPI=new AccountAPI(AccoutSetting.accessToken);
				accountAPI.getUid(new RequestListener() {
					
					public void onIOException(IOException arg0) {
						// TODO Auto-generated method stub

					}
					
					public void onError(WeiboException arg0) {
						// TODO Auto-generated method stub

					}
					
					public void onComplete(String arg0) {
						// TODO Auto-generated method stub
						int n=arg0.indexOf(":");
						int m=arg0.indexOf("}");
						AccessSinaUserId.keepUidAccessToken(AccoutSetting.this, arg0.substring(n+1,m));
						Log.e("sina", arg0);
						String uid=AccessSinaUserId.readUidAccessToken(AccoutSetting.this);
						UsersAPI usersAPI=new UsersAPI(AccoutSetting.accessToken);
						Log.e("sina", uid);
						usersAPI.show(Long.parseLong(uid), new getSinaUserInfoListener());
					}
				});
				
			}
		}

		public void onCancel() {
			// TODO Auto-generated method stub
			
		}

		public void onError(WeiboDialogError arg0) {
			// TODO Auto-generated method stub
			Message msg=new Message();
			msg.what=4;
			AccoutSetting.this.myHandler.sendMessage(msg);
		}

		public void onWeiboException(WeiboException arg0) {
			// TODO Auto-generated method stub
			Message msg=new Message();
			msg.what=4;
			AccoutSetting.this.myHandler.sendMessage(msg);
		}
	}
	
	public class getSinaUserInfoListener implements RequestListener{

		public void onComplete(String arg0) {
			// TODO Auto-generated method stub
			int index=arg0.indexOf("screen_name");
			arg0=arg0.substring(index);
			int index2=arg0.indexOf(",");
			String name=arg0.substring(14,index2-1);
			AccessSinaUserInfo.keepUserInfo(AccoutSetting.this, name);		
			AccoutSetting.accessToken=AccessSinaTokenKeeper.readSinaAccessToken(AccoutSetting.this);
			
			Message msg=new Message();
			msg.what=1;
			AccoutSetting.this.myHandler.sendMessage(msg);
		}

		public void onError(WeiboException arg0) {
			// TODO Auto-generated method stub
		}

		public void onIOException(IOException arg0) {
			// TODO Auto-generated method stub
		}
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (requestCode==123) {
            if (resultCode==OAuthV1AuthorizeWebView.RESULT_CODE)    {
                oauth=(OAuthV1) data.getExtras().getSerializable("oauth");
                try {
              	  oauth=OAuthV1Client.accessToken(oauth);
                } catch (Exception e1) {
                    e1.printStackTrace();
                } 
                AccessQqTokenKeeper.keepQqAccessToken(AccoutSetting.this, oauth);
                Toast.makeText(AccoutSetting.this, "qq认证成功",Toast.LENGTH_LONG).show();
              
                UserAPI userAPI=new UserAPI(OAuthConstants.OAUTH_VERSION_1);
                   String useInfo;
				try {
					useInfo = userAPI.info(oauth, "json");
					int index=useInfo.indexOf("\"nick\"");
					useInfo=useInfo.substring(index);
					int index2=useInfo.indexOf("\",\"");
					useInfo=useInfo.substring(8,index2);
					
					AccessQqUserInfo.keepQqUser(AccoutSetting.this, useInfo);			
					
					qqBind();
					AccessSinaUserInfo.keepUserInfoBind(AccoutSetting.this, false);
					AccessQqUserInfo.keepQqUserBind(AccoutSetting.this, true);
	            	
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}			
                userAPI.shutdownConnection();
                
            }else{
            	Toast.makeText(AccoutSetting.this, "qq认证失败",Toast.LENGTH_LONG).show();
            }
		}
	}
}
